<!--核对完成
出库单界面中可以实现如下操作:
  // XX仓库>出库单记录
  allOutStoreOrder: 'allOutStoreOrder',
  // XX仓库>无单出库单
  simpleOutStoreOrder: 'simpleOutStoreOrder',
-->

<template>
	<!-- 无单出库单页面 -->
	<a-card :bordered="false">
		<div class="table-page-search-wrapper">
			<a-form layout="inline">
				<a-row :gutter="48">

					<a-col :md="8" :sm="24">
						<a-form-item label="出库单号">
							<a-input v-model="queryParam.orderNumber" placeholder="请输入出库单号" />
						</a-form-item>
					</a-col>
					<a-col :md="8" :sm="24">
						<a-form-item label="备注">
							<a-input v-model="queryParam.remark" placeholder="请输入备注" />
						</a-form-item>
					</a-col>
					<!-- <a-col :md="4" :sm="24" v-show="$isDev">
            <a-form-item label="订单类型">
              <a-select :default-value="orderType" v-model="queryParam.orderType"
                        style="width: 120px">
                <a-select-option :value="item.id" v-for="(item, index) in orderTypeList">
                  {{ item.name }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col> -->

					<!-- <a-col :md="4" :sm="24" v-show="$isDev">
            <a-form-item label="执行状态">
              <a-select :default-value="executeStatus" v-model="queryParam.executeStatus"
                        style="width: 120px">
                <a-select-option :value="id" v-for="{id, name, code} in executeStatusList">
                  {{ name }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col> -->

					<a-col :md="!advanced && 8 || 24" :sm="24">
						<span class="table-page-search-submitButtons"
							:style="advanced && { float: 'right', overflow: 'hidden' } || {}">
							<a-button type="primary" @click="$refs.table.refresh(true)">查询</a-button>
							<a-button style="margin-left: 8px"
								@click="() => { queryParam.remark = null; queryParam.orderNumber = null; $refs.table.refresh(true) }">重置</a-button>
						</span>
					</a-col>

					<!-- <a-col :md="24" :sm="24">
            <a-form-item label="供应商：">
              <a-radio-group default-value="" button-style="solid" v-model="queryParam.orgIdSupplier">
                <a-radio-button value="">
                  全部
                </a-radio-button>
                <a-radio-button :value="id" v-for="{id, name} in suppliers">
                  {{ name }}
                </a-radio-button>
              </a-radio-group>
            </a-form-item>
          </a-col> -->

					<!-- <a-col :md="24" :sm="24">
            <a-form-item label="归属公司：">
              <a-radio-group default-value="" button-style="solid" v-model="queryParam.orgIdCompany">
                <a-radio-button value="">
                  全部
                </a-radio-button>
                <a-radio-button :value="id" v-for="{id, name} in orgs">
                  {{ name }}
                </a-radio-button>
              </a-radio-group>

            </a-form-item>
          </a-col> -->

				</a-row>
			</a-form>
		</div>

		<s-table ref="table" size="default" :columns="columnsDynamic" :data="loadData" :alert="true"
			:rowKey="(record) => record.code" :rowSelection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }">

			<span :slot="$util.EMS_ORDER_VIEW_STATE.waitOutStoreByProductionOrder" slot-scope="text, record">
				<a @click="$refs.productionOutStoreAddForm.show(record, '出库', '', { 'viewState': 'materialOut', materialType })">
					出库</a>
				<a-divider type="vertical" />
				<a @click="$refs.productionOutStoreDetailForm.show(record, '出库详情', 'materialOut', { materialType })">
					出库详情</a>
			</span>

			<span :slot="$util.EMS_ORDER_VIEW_STATE.completedOutStoreByProductionOrder" slot-scope="text, record">
				<!--     生产单已出库   -->
				<a @click="$refs.productionOutStoreDetailForm.show(record, '出库详情', 'materialOut', { materialType })">出库详情</a>
				<a-divider type="vertical" />
				<!--    实际上是查出库订单,显示订单Modal    -->
				<a
					@click="$refs.orderIndexModal.show(record, '出库明细', 'outOrder', { 'orderType': $businessEnum.ORDER_TYPE_ENUM.outOrder.id })">出库明细</a>
			</span>

			<span :slot="$util.EMS_ORDER_VIEW_STATE.allOutStoreOrder" slot-scope="text, record">
				<!--     出库单记录 > 出库单明细   -->
				<a @click="$refs.outOrderDetailForm.show(record, '出库明细', '', { 'orderId': record.orderId })">出库明细</a>
			</span>

			<span :slot="$util.EMS_ORDER_VIEW_STATE.simpleOutStoreOrder" slot-scope="text, record">
				<!--     出库单记录 > 出库单明细   -->
				<a @click="$refs.detailForm.show(record, '出库详情', 'packingOutReadonly')">出库详情</a>
			</span>

		</s-table>

		<out-order-detail-form ref="outOrderDetailForm" />
		<detail-form ref="detailForm" @ok="$refs.table.refresh()" />

	</a-card>
</template>

<script>
import { STable } from '@/components'
import { page, changeStatus, del, doScheduleProduction, doRecommendedProduction, doMaterialCalculation } from '@/api/modular/main/emsorder/emsOrderManage'
import { list as emsOrgList } from '@/api/modular/main/emsorg/emsOrgManage'

import outOrderDetailForm from '@/views/main/emsordermaterial/outOrder/emsOutOrderDetailForm'
import detailForm from '@/views/main/materialManagement/simpleOutOrder/detailForm'

export default {
	components: {
		STable,
		outOrderDetailForm,
		detailForm,
	},
	data() {
		return {
			advanced: false, // 高级搜索 展开/关闭
			queryParam: {},  // 查询参数
			columns: [       // 表头
				{
					title: '订单号',
					dataIndex: 'orderNumber'
				},
				{
					title: '生产单号',
					dataIndex: 'parentNumber'
				},
				{
					title: '订单类型',
					dataIndex: 'orderTypeStr'
				},
				{
					title: '是否可用',
					dataIndex: 'status',
					scopedSlots: { customRender: 'status' }
				},
				{
					title: '进度状态',
					dataIndex: 'executeStatusStr'
				},
				{
					title: '创建时间',
					dataIndex: 'createTime'
				},
				{
					title: '备注',
					dataIndex: 'remark',
					ellipsis: true
				},
				{
					title: '操作',
					dataIndex: 'action',
					width: '150px',
					scopedSlots: { customRender: 'action' }
				}
			],
			// 加载数据方法 必须为 Promise 对象
			loadData: parameter => {
				// let ot = this.orderType
				this.queryParam.materialType = this.materialTypeUrlParam
				return page(Object.assign(parameter, this.queryParam)).then((res) => {
					return res.data
				})
			},
			scheduleProductionVisible: false,
			selectedRowKeys: [],
			selectedRows: [],
			defaultExpandedKeys: [],
			replaceFields: {
				key: 'id',
			},
			urlParam: {},
			columnsType: '',
			suppliers: [],
			orgs: [],
			viewState: '',
			materialType: '',
		}
	},
	computed: {
		routePath() {
			let urlParam = this.$util.getUrlParam(this.$route.path)
			return urlParam
		},
		materialTypeUrlParam() {
			return this.routePath.materialType
		},
		materialTypeEnum() {
			return this.$util.findMaterialTypeById(this.materialType)
		},
		orderType() {
			return this.routePath.orderType
		},
		orderTypeList() {
			let result = []
			result.push({ id: '', name: '全部', code: 'all' })
			for (const key in this.$businessEnum.ORDER_TYPE_ENUM) {
				let value = this.$businessEnum.ORDER_TYPE_ENUM[key]
				result.push(value)
			}
			return result
		},
		executeStatus() {
			return this.urlParam.executeStatus
		},
		executeStatusList() {
			let result = []
			result.push({ id: '', name: '全部', code: 'all' })
			for (const key in this.$businessEnum.EXECUTE_STATUS_ENUM) {
				let value = this.$businessEnum.EXECUTE_STATUS_ENUM[key]
				result.push(value)
			}
			return result
		},
		columnsDynamic() {
			switch (this.viewState) {
				case this.$util.EMS_ORDER_VIEW_STATE.allOutStoreOrder:
					return [
						{
							title: '序号', width: '80px',
							customRender: (text, record, index) => `${index + 1}`
						},
						{
							title: '出库单号',
							dataIndex: 'orderNumber'
						},
						{
							title: '生产单号',
							dataIndex: 'parentNumber'
						},
						{
							title: '出库时间',
							dataIndex: 'createTime'
						},
						{
							title: '备注',
							dataIndex: 'remark',
							ellipsis: true
						},
						{
							title: '操作',
							dataIndex: 'action',
							width: '250px',
							scopedSlots: { customRender: this.$util.EMS_ORDER_VIEW_STATE.allOutStoreOrder }
						}
					]
				case this.$util.EMS_ORDER_VIEW_STATE.simpleOutStoreOrder:
					return [
						{
							title: '序号', width: '80px',
							customRender: (text, record, index) => `${index + 1}`
						},
						{
							title: '出库单号',
							dataIndex: 'orderNumber'
						},
						{
							title: '生产单号',
							dataIndex: 'parentNumber'
						},
						// {
						//   title: '物料总数量',
						//   dataIndex: '',
						//   customRender: (text, record, index) => `【没算】`
						// },
						{
							title: '出库时间',
							dataIndex: 'createTime'
						},
						{
							title: '备注',
							dataIndex: 'remark',
							ellipsis: true
						},
						{
							title: '操作',
							dataIndex: 'action',
							width: '250px',
							scopedSlots: { customRender: this.$util.EMS_ORDER_VIEW_STATE.simpleOutStoreOrder }
						}
					]
				default:
					return []
			}
		}
	},
	watch: {
		'$route.path': function (newValue) {
			let urlParam = this.$util.getUrlParam(this.$route.path)
			this.urlParam = urlParam
			let { orderType, executeStatus, columnsType, viewState, materialType, refCount } = urlParam
			this.setParam(columnsType, viewState, materialType, orderType, executeStatus, refCount)

			setTimeout(() => {
				this.handleOk()
				this.$refs.table.clearSelected()
			}, 100)
		}
	},
	created() {
		let urlParam = this.$util.getUrlParam(this.$route.path)
		this.urlParam = urlParam
		let { orderType, executeStatus, columnsType, viewState, materialType, refCount } = urlParam
		this.setParam(columnsType, viewState, materialType, orderType, executeStatus, refCount)
		this.suppliers = this.$util.getOrgList([this.$businessEnum.ORG_TYPE_ENUM.PRIMARY_SUPPLIER.id, this.$businessEnum.ORG_TYPE_ENUM.NORMAL_SUPPLIER.id])
		this.orgs = this.$util.getOrgList([this.$businessEnum.ORG_TYPE_ENUM.COMPANY.id])
	},
	methods: {
		setParam: function (columnsType, viewState, materialType, orderType, executeStatus, refCount) {
			this.columnsType = columnsType
			this.viewState = viewState
			this.materialType = materialType
			this.queryParam = { orderType: orderType || '', executeStatus: executeStatus || '' }
			this.queryParam.refCount = refCount
			// 如果是查无单入库单。则源引ID必须为0
			this.queryParam.sourceOrderId = viewState == this.$util.EMS_ORDER_VIEW_STATE.simpleOutStoreOrder ? 0 : null
		},
		del(record) {
			del(record).then((res) => {
				if (res.success) {
					this.$message.success('删除成功')
					this.$refs.table.refresh()
				} else {
					this.$message.error('删除失败：' + res.message)
				}
			}).catch((err) => {
				this.$message.error('删除错误：' + err.message)
			})
		},
		toggleAdvanced() {
			this.advanced = !this.advanced
		},
		handleOk() {
			this.$refs.table.refresh()
		},
		onSelectChange(selectedRowKeys, selectedRows) {
			this.selectedRowKeys = selectedRowKeys
			this.selectedRows = selectedRows
		},
		onOrderStatusChange(checked, row) {
			row.loading = true
			let { orderId } = row
			let status = checked ? 0 : 1
			let parameter = { orderId, status }
			changeStatus(parameter).then(res => {
				this.handleOk()
			})
		},
		// 排单生产
		handleScheduleProductionShow() {
			if (this.validateScheduleProduction()) {
				this.scheduleProductionVisible = true
			}
		},
		validateScheduleProduction() {
			let selectedRows = this.selectedRows
			if (selectedRows.length == 0) {
				this.$message.error('请先选择要排单生产的订单')
				return false
			}
			let unavailableOrders = selectedRows.filter(value => value.status != 0)
			if (unavailableOrders.length > 0) {
				this.$message.error('订单状态必须为"可用"才可以进行排单')
				return false
			}
			return true
		},
		handleOkByScheduleProduction() {
			// 调接口,排单生产
			if (this.validateScheduleProduction()) {
				let orderIds = this.selectedRows.map(value => value.orderId).join(',')
				doScheduleProduction({ orderIds }).then(res => {
					this.$message.success(res.message)
				})
			}
		},
		handleRecommendedProduction() {
			// 推荐生产
		},
		handleMaterialCalculation() {
			// 物料计算
			let orderIds = this.selectedRows.map(row => row.orderId).join(',')
			this.$refs.materialCalculationForm.add(orderIds)
			// doMaterialCalculation({orderIds: selectedRowKeys}).then((res) => {
			//   let data = res.data
			//
			// })
		},
		getSuppliers() {
			emsOrgList({ pid: '1473297518794452994', unitRanId: this.$businessEnum.ORG_TYPE_ENUM.PRIMARY_SUPPLIER.id }).then((res) => {
				this.suppliers = res.data
			})
		},
		getOrgs() {
			emsOrgList({ pid: '1473297518794452994', unitRanId: this.$businessEnum.ORG_TYPE_ENUM.COMPANY.id }).then((res) => {
				this.orgs = res.data
			})
		}
	}
}
</script>

<style lang="less">
.table-operator {
	margin-bottom: 18px;
}

button {
	margin-right: 8px;
}
</style>
